package com.community.common.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.common.config.BizException;
import com.community.common.enums.CameraPermissionEnum;
import com.community.common.mapper.ManagerUserMapper;
import com.community.common.mapper.OwnerHouseMapper;
import com.community.common.mapper.PublicUserMapper;
import com.community.common.mapper.UserPermissionMapper;
import com.community.common.pojo.PageRequest;
import com.community.common.pojo.domain.ManagerUser;
import com.community.common.pojo.domain.OwnerHouse;
import com.community.common.pojo.domain.PublicUser;
import com.community.common.pojo.dto.BindToWxDto;
import com.community.common.pojo.dto.FindOwnerDto;
import com.community.common.pojo.dto.PublicUserCondition;
import com.community.common.pojo.response.CodeEnum;
import com.community.common.pojo.response.MyResponse;
import com.community.common.pojo.vo.OwnerInfoVo;
import com.community.common.pojo.vo.PublicUserVo;
import com.community.common.pojo.vo.UserPermissionDto;
import com.community.common.pojo.vo.WXPublicUserVo;
import com.community.common.util.CommonUtil;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 公众号用户表 服务实现类
 * </p>
 *
 * @author superman
 * @since 2020-08-02
 */
@Slf4j
@Service
public class PublicUserService extends ServiceImpl<PublicUserMapper, PublicUser> {

    @Resource
    private PublicUserMapper publicUserMapper;
    @Resource
    private UserPermissionMapper userPermissionMapper;
    @Resource
    private ManagerUserMapper managerUserMapper;
    @Resource
    private CameraService cameraService;
    @Resource
    private CommunityService communityService;

    public List<PublicUserVo> queryByPageAll(PageRequest<PublicUserCondition> pageRequest, String communityId, String checkState) {
        PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        return publicUserMapper.queryByPage(pageRequest.getCondition(), communityId, checkState);
    }

    public List<PublicUserVo> queryByPageBlack(PageRequest<PublicUserCondition> pageRequest, String communityId) {
        PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        return publicUserMapper.queryByPageBlack(pageRequest.getCondition(), communityId);
    }

    public MyResponse saveUser(WXPublicUserVo wxPublicUserVo) {
        PublicUser publicUser = new PublicUser();
        try {
            BeanUtils.copyProperties(publicUser, wxPublicUserVo);
        } catch (Exception e) {
            log.error("wxPublicUserVo转换出错。");
            throw new BizException(e.getMessage());
        }
        publicUser.setId(CommonUtil.getIdStr());
        publicUser.setCreateTime(LocalDateTime.now());
        publicUser.setUpdateTime(LocalDateTime.now());
        int insert = baseMapper.insert(publicUser);
        log.info("新增用戶：{}", publicUser);
        if (insert == 1) {
            return MyResponse.success();
        }
        return MyResponse.fail();
    }

    public MyResponse updateUser(WXPublicUserVo wxPublicUserVo) {
        log.info("更新用户 wxPublicUserVo:{}", wxPublicUserVo);

        LambdaQueryWrapper<PublicUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PublicUser::getId, wxPublicUserVo.getId());
        PublicUser publicUser = getOne(queryWrapper);
        // 修改信息
        try {
            BeanUtils.copyProperties(publicUser, wxPublicUserVo);
        } catch (Exception e) {
            log.error(" BeanUtils.copyProperties error ", e);
        }
        publicUser.setUpdateTime(LocalDateTime.now());
        // 修改用户信息
        baseMapper.updateById(publicUser);
        return MyResponse.success();
    }

    @Resource
    private OwnerHouseMapper ownerHouseMapper;

    public MyResponse findOwner(FindOwnerDto findOwnerDto) {
        ArrayList<OwnerInfoVo> ownerInfoVos = null;
        try {
            Set<PublicUser> publicUsers = ownerHouseMapper.selectByCommunityAndName(findOwnerDto);
            ownerInfoVos = new ArrayList<>();
            for (PublicUser publicUser : publicUsers) {
                ownerInfoVos.add(OwnerInfoVo.builder()
                        .name(publicUser.getName())
                        .id(publicUser.getId())
                        .openId(publicUser.getOpenId())
                        .phone(publicUser.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")).build());
            }
        } catch (Exception e) {
            log.error("findOwner error ", e);
        }
        return MyResponse.success(ownerInfoVos);
    }

    public List<PublicUserVo> queryToBind(PageRequest<PublicUserCondition> pageRequest) {
        PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        return publicUserMapper.queryByPage(pageRequest.getCondition(), null, "1");
    }

    public MyResponse bindToWx(BindToWxDto bindToWxDto) {
        ManagerUser managerUser = managerUserMapper.selectById(bindToWxDto.getManageUserId());
        if (managerUser == null) {
            return MyResponse.fail(CodeEnum.NOT_FOUND);
        }
        managerUser.setPublicId(bindToWxDto.getPublicUserId());
        managerUser.setUpdateTime(LocalDateTime.now());
        managerUserMapper.updateById(managerUser);
        return MyResponse.success();
    }

    public List<UserPermissionDto> getUserPermission(String communityId, String openId) {
        Set<UserPermissionDto> list = publicUserMapper.getUserPermission(communityId, openId);
        for (UserPermissionDto permissionDto : list) {
            if (permissionDto.getCurrentAllow() == 1 && permissionDto.getTargetAllow() == 1
                    && permissionDto.getCommandStatus() == 3) {
                permissionDto.setUserPermission(CameraPermissionEnum.success.getCode());
            } else if (permissionDto.getCurrentAllow() == 0 && permissionDto.getTargetAllow() == 0
                    && permissionDto.getCommandStatus() == 3) {
                permissionDto.setUserPermission(CameraPermissionEnum.fail.getCode());
            } else {
                permissionDto.setUserPermission(CameraPermissionEnum.unkonwn.getCode());
            }
        }
        return new ArrayList<>(list);
    }

    /**
     * 根据openid校验用户是否是业主
     * @param openId
     */
    public boolean whetherOwner(String openId) {
        LambdaQueryWrapper<OwnerHouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OwnerHouse::getOpenId,openId);
        queryWrapper.eq(OwnerHouse::getCheckState,"1");
        List<OwnerHouse> ownerHouses = ownerHouseMapper.selectList(queryWrapper);
        return CollectionUtils.isNotEmpty(ownerHouses);
    }

}
